/**
 * Copyright 2011 FeedDreamwork SIG
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.feeddreamwork.feed;

import java.io.*;
import java.util.*;

import org.feeddreamwork.*;
import org.w3c.dom.*;

import com.google.appengine.api.utils.*;

public abstract class FeedBuilder {
	protected final Document feedDocument;
	protected final Feed source;
	protected final String feedId;

	public FeedBuilder(Feed source, String feedId) {
		Utils.throwIfNull(source);
		Utils.throwIfNullOrEmpty(feedId);
		this.source = source;
		this.feedId = feedId;
		feedDocument = XMLUtils.newDocument();
	}

	public void build(Writer writer) {
		Element root = buildRoot();
		buildMetadata(root);
		for (Entry entry : source.getEntries())
			buildEntry(root, entry);
		XMLUtils.outputNode(feedDocument, writer);
	}

	public String build() {
		StringWriter resultWriter = new StringWriter();
		build(resultWriter);
		return resultWriter.toString();
	}

	public String getGeneratorInfo() {
		return SystemProperty.applicationId.get() + " - "
				+ this.getClass().getName() + " " + ApplicationProperty.VERSION;
	}

	public String getFeedAddress() {
		return ApplicationProperty.HOST_NAME + "/feed/" + feedId;
	}

	public abstract String addUpdatedTime(String source, Date updatedTime);

	public abstract String getMIMEType();

	protected abstract Element buildRoot();

	protected abstract void buildMetadata(Element root);

	protected abstract Element buildEntry(Element root, Entry entry);
}
